package com.ifeedme.rocketremote
{
	/**
	 * @author Jim Hayes (www.ifeedme.com) may 2007
	 * The "apollo" prefs object uses xml files on the local filesystem as it's storage mechanism.
	 * 
	 */	
	
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	
	public class PrefsObjectAir extends PrefsObject implements IPrefsObject
	{
		
		private var _frontendsFile:File;
		private var _frontendsFileName:String = "frontends.xml";
		
		private var _keyMapFile:File;
		private var _keyMapFileName:String = "keymap.xml";
		
		function PrefsObjectAir():void
		{
			super();
			_frontendsFile = File.applicationStorageDirectory;            	
			_frontendsFile = _frontendsFile.resolvePath(_frontendsFileName);
			_keyMapFile = File.applicationDirectory;
			_keyMapFile = _keyMapFile.resolvePath(_keyMapFileName);
		}
		
		//
		override public function readPrefs():void
		{
			readFrontends();
			readKeyMap();
			signalReady();
		}
		
		override protected function readFrontends():void
		{
			if(_frontendsFile.exists) 
			{
				_frontends = readXmlFIle(_frontendsFile);
			} 
			else 
			{
				firstRun();				
			}
		}
		
		override protected function readKeyMap():void
		{
			_keyMapXml = readXmlFIle(_keyMapFile);
		}
		
		override public function writePrefs(str:String):void
		{
			writeXmlFile(_frontendsFile,str);
		}
		
		override public function writeKeyMap(keyMapXml:XML):void
		{
			var str:String = keyMapXml.toString();
			writeXmlFile(_keyMapFile,str);
		}
		
		private function readXmlFIle(file:File):XML
		{
			var xmlReturn:XML;
			if(file.exists) 
			{
				var stream:FileStream = new FileStream(); 				
			
				stream.open(file, FileMode.READ);
				try
				{				
					xmlReturn = XML(stream.readUTFBytes(stream.bytesAvailable));
				}
				catch(e:Error)
            	{
            		// probably an xml parse error
            		trace("Failed to parse xml file : " + file.nativePath + "\n" + e.message); 
            	}
				
				stream.close();   					
											
			} 
			else 
			{
				trace("keymap file " + file.nativePath + " does not exist.");
			}
			return xmlReturn;
		}
		
		private function writeXmlFile(file:File,str:String):void
		{
			str = '<?xml version="1.0" encoding="utf-8"?>\n'+ str;
			str = str.replace(/\n/g, File.lineEnding);
			
			var stream:FileStream = new FileStream();			
			stream.open(file, FileMode.WRITE);	
			stream.writeUTFBytes(str);
			stream.close();
		}
				
	}
}